from pydub.playback import play
from pydub import AudioSegment
from random import randint
from _thread import start_new_thread

def play_random_segment_of_music(music_filename, segment_length=5000, start_time=None):
    # segment_length：片段长度
    # start_time ：前多少秒不要

    song = AudioSegment.from_wav(music_filename)#读取音乐片段
    if segment_length > song.duration_seconds*1000/2:
        segment_length = int(song.duration_seconds*1000/2)
    if not start_time:
        start_time = randint(0, int(song.duration_seconds*1000) - segment_length)#开始时间，以毫秒表示
    song_segment = song[int(start_time): int(start_time)+segment_length]
    while not check_segment_OK(song_segment):
        start_time = randint(0, int(song.duration_seconds*1000) - segment_length)#开始时间，以毫秒表示
        song_segment = song[int(start_time): int(start_time)+segment_length]
    thread_id = start_new_thread(play,(song_segment,))
    return start_time, thread_id

def check_segment_OK(segment, song=None):
    if song:
        if segment.rms < song.rms/6:#该片段声音太小（相对值）
            return False
    else:
        if segment.rms < 1000:#该片段绝对声音太小（绝对值）
            return False
    return True

if __name__ == "__main__":
    play_random_segment_of_music("music/test.wav")

# play(song)
# playsound("test.mp3")